const { default: axios } = require("axios");
const { userModel } = require("../model/index");
const { cid, redirect_uri, client_secret } = require("../config");
const { createToken } = require("../middleware/jwt");

module.exports = {
  //创建用户
  async createUserService(userProps) {
    const { username, password } = userProps;
    const user = await userModel.create({
      username,
      password,
      email: username,
      ...userProps,
    });
    return user;
  },
  //根据用户名查询用户
  async findByUsername(username) {
    const user = await userModel.findOne({ username });
    return user;
  },
  //根据手机号查询用户
  async findByPhoneNumber(phoneNumber) {
    const user = await userModel.findOne({ phoneNumber });
    return user;
  },
  //根据用户名称与用户密码查询
  async findByUsernameAndPassword({ username, password }) {
    const user = await userModel.findOne({ username, password });
    return user;
  },
  //获取accessToken
  async getAccessToken(code) {
    const result = await axios.post("https://gitee.com/oauth/token", {
      client_id: cid,
      client_secret: client_secret,
      code,
      redirect_uri: redirect_uri,
      grant_type: "authorization_code",
    });
    return result.data;
  },
  //根据accessToken获取用户信息
  async getUserInfoByAccessToken(accessToken) {
    try {
      const result = await axios.get(
        `https://gitee.com/api/v5/user?access_token=${accessToken}`
      );
      return result.data;
    } catch (error) {
      throw new Error("gitee请求失败", error);
    }
  },
  async loginByGitee(code) {
    const { access_token } = await this.getAccessToken(code);
    const data = await this.getUserInfoByAccessToken(access_token);
    let token = "";
    if (data) {
      const user = await this.findByUsername(`gitee${data.id}`);

      if (user) {
        token = await createToken({ username: user.username, id: user._id, _id: user._id });
      } else {
        const newUser = await userModel.create({
          username: `gitee${data.id}`,
          nickname: data.name || "",
          picure: data.avatar_url || "",
          email: data.email ?? "",
          oauthId: data.id,
          type: "oauth",
          provider: "gitee",
        });
        token = await createToken({
          username: newUser.username,
          id: newUser._id,
          _id: newUser._id
        });
      }
    }
    return token;
  },
  //修改用户信息
  async updateUserService(userProps) {
    const { id } = userProps;
    delete userProps.id;
    console.log(userProps);

    const user = await userModel.findByIdAndUpdate(id, userProps, {
      new: true,
    });
    return user;
  },
  //删除用户
  async deleteUserService(id) {
    const user = await userModel
      .findByIdAndDelete(id)
      .select("id username nickname");
    return user;
  },
  //查询用户信息
  async getUserInfoService(id) {
    const user = await userModel.findById(id).lean();
    return user;
  }
};
